package com.yuhf.db.factory;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.yuhf.db.utils.DBConnection;

import edu.yuhf.dao.iface.UserDao;

public class DaoFactory {
	private static final String databaseType;
	
	private static Logger log=Logger.getLogger(DaoFactory.class);
	
	static {
		Properties prop=new Properties();
		try {
			prop.load(DBConnection.class.getResourceAsStream("/jdbc.properties"));
		} catch (IOException e) {
			log.error("jdbc.properties file not found,the exception is:"+e.getLocalizedMessage());
		}
		String dbType=prop.getProperty("database.type").toLowerCase();
		switch(dbType) {
			case "oracle":databaseType="Oracle";break;
			case "mysql":databaseType="MySQL";break;
			default:databaseType="Oracle";break;
		}

	}

	@SuppressWarnings("unchecked")
	public static UserDao createUserDao()  {
		Class<UserDao> userDaoImplClass=null;
		UserDao userDao=null;
		String className = "edu.yuhf.dao.[databaseType1].User[databaseType2]DaoImpl";
		if (databaseType != null && !databaseType.equals("")) {
			className=className.replace("[databaseType1]",databaseType.toLowerCase());
			className=className.replace("[databaseType2]",databaseType);
			log.debug(className);
			try {
				userDaoImplClass = (Class<UserDao>) Class.forName(className);
				userDao=userDaoImplClass.getDeclaredConstructor().newInstance();
			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
				log.error("userDao create error! message is:"+e.getMessage());
			}
			return userDao;
		}
		return null;
	}
}
